package com.pmt.feedplayer.data

import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.media.ThumbnailUtils
import android.provider.MediaStore
import androidx.core.database.getStringOrNull
import java.io.File
import java.io.FileOutputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext

/**
 * 本地视频扫描器
 * 用于扫描设备上的视频文件并返回VideoItem列表
 */
actual class LocalVideoScanner {
    // 应用上下文（从外部传入）
    private lateinit var context: Context
    
    /**
     * 设置上下文
     */
    fun setContext(context: Context) {
        this.context = context
    }
    
    /**
     * 扫描本地视频文件
     * @param offset 偏移量，跳过前面的视频数量
     * @param limit 返回的最大视频数量
     * @return 视频列表
     */
    actual suspend fun scanLocalVideos(offset: Int, limit: Int): List<VideoItem> = withContext(Dispatchers.IO) {
        val videos = mutableListOf<VideoItem>()
        
        // 定义要查询的视频文件的列
        val projection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.SIZE
        )
        
        // 排序方式：按修改时间倒序，最新的视频在前面
        val sortOrder = "${MediaStore.Video.Media.DATE_MODIFIED} DESC"
        
        try {
            val cursor: Cursor? = context.contentResolver.query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,
                null,
                sortOrder
            )
            
            cursor?.use { c ->
                val idColumn = c.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
                val dataColumn = c.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)
                val nameColumn = c.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)
                val durationColumn = c.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)
                val sizeColumn = c.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)
                
                // 跳过offset个视频
                if (offset > 0) {
                    c.moveToPosition(offset - 1)
                }
                
                // 只取前limit个视频
                var count = 0
                val videoInfoList = mutableListOf<Triple<String, String, String>>()
                
                // 先收集所有需要的视频信息
                while (c.moveToNext() && count < limit) {
                    val id = c.getLong(idColumn).toString()
                    val filePath = c.getString(dataColumn)
                    val fileName = c.getString(nameColumn)
                    val duration = c.getLong(durationColumn)
                    val fileSize = c.getLong(sizeColumn)
                    
                    // 验证文件是否存在
                    if (File(filePath).exists()) {
                        videoInfoList.add(Triple(id, filePath, fileName))
                        videos.add(VideoItem(
                            id = id,
                            videoUrl = filePath,
                            thumbnailUrl = "", // 先设为空，稍后异步填充
                            title = fileName,
                            duration = duration,
                            authorName = "本地文件",
                            likeCount = 0,
                            viewCount = 0
                        ))
                        count++
                    }
                }
                
                // 异步生成缩略图，提高性能
                val deferredThumbnails = videoInfoList.mapIndexed { index, (id, filePath, _) ->
                    async(Dispatchers.IO) {
                        // 检查缓存中是否已有缩略图
                        val thumbnailPath = getThumbnailPathFromCache(context, id)
                        if (thumbnailPath.isNotEmpty()) {
                            // 缓存命中，直接使用
                            Pair(index, thumbnailPath)
                        } else {
                            // 生成新缩略图并缓存
                            Pair(index, generateAndCacheVideoThumbnail(context, filePath, id))
                        }
                    }
                }
                
                // 等待所有缩略图生成完成
                val thumbnailResults = awaitAll(*deferredThumbnails.toTypedArray())
                
                // 更新视频项的缩略图路径
                thumbnailResults.forEach { (index, thumbnailPath) ->
                    if (index < videos.size) {
                        videos[index] = videos[index].copy(thumbnailUrl = thumbnailPath)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        
        return@withContext videos
    }
    
    /**
     * 从缓存获取缩略图路径
     * @param context 上下文
     * @param videoId 视频ID
     * @return 缩略图文件路径，如果不存在返回空字符串
     */
    private fun getThumbnailPathFromCache(context: Context, videoId: String): String {
        val cacheDir = File(context.cacheDir, "video_thumbnails")
        if (!cacheDir.exists()) {
            return ""
        }
        
        val thumbnailFile = File(cacheDir, "thumb_$videoId.jpg")
        return if (thumbnailFile.exists()) {
            thumbnailFile.absolutePath
        } else {
            ""
        }
    }
    
    /**
     * 生成并缓存视频缩略图
     * @param context 上下文
     * @param videoPath 视频文件路径
     * @param videoId 视频ID
     * @return 缩略图文件路径
     */
    private fun generateAndCacheVideoThumbnail(context: Context, videoPath: String, videoId: String): String {
        try {
            // 生成视频缩略图，设置更高效的编码参数
            // 使用MINI_KIND (512x384) 平衡质量和性能
            val thumbnail = ThumbnailUtils.createVideoThumbnail(
                videoPath,
                MediaStore.Video.Thumbnails.MINI_KIND
            )
            
            if (thumbnail != null) {
                // 获取应用缓存目录
                val cacheDir = File(context.cacheDir, "video_thumbnails")
                if (!cacheDir.exists()) {
                    cacheDir.mkdirs()
                }
                
                // 创建缩略图文件
                val thumbnailFile = File(cacheDir, "thumb_$videoId.jpg")
                
                // 保存缩略图到文件，使用try-with-resources确保流正确关闭
                FileOutputStream(thumbnailFile).use { outputStream ->
                    // 设置压缩质量为60，与iOS端保持一致，平衡性能和显示效果
                    thumbnail.compress(Bitmap.CompressFormat.JPEG, 60, outputStream)
                    outputStream.flush()
                }
                
                return thumbnailFile.absolutePath
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        
        // 如果无法生成缩略图，返回空字符串
        return ""
    }
}